package com.km.core.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.google.common.collect.Lists;
import com.km.core.dto.BaseDto;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>fast json打印输出过滤字段</p>
 * Created by zhezhiyong@163.com on 2017/5/11.
 */
public class CustomPropertyPreFilter implements PropertyFilter {

    private List<String> fields = new ArrayList<>();

    public CustomPropertyPreFilter(List<String> fields) {
        this.fields = fields;
    }

    public static void main(String[] args) {
        PropertyFilter propertyFilter = new CustomPropertyPreFilter(Lists.newArrayList("name"));
        BaseDto dto = new BaseDto();
        dto.put("name", "123");
        dto.put("age", "21");
        System.out.println(JSON.toJSONString(dto, propertyFilter));
    }

    @Override
    public boolean apply(Object source, String name, Object value) {

        for (String field : fields) {
            if (name.equals(field))
                return false;
        }
        return true;
    }
}
